package com.ming.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        //创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个selector对象
        Selector selector = Selector.open();

        //绑定一个端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel 注册到 selector 关心事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true){
            if (selector.select(1000)==0){
                System.out.println("wait 1s, no collection");
                continue;
            }
            //如果返回的大于零(表明已经获取到关注的时间) 就获取到相关的 selectionKey 集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //通过selectionKeys 反向获取通道
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();

                if (key.isAcceptable()){//如果是OP_ACCEPT 有新的客户端连接
                    //给客户端生成一个 socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个socketChannel"+socketChannel.hashCode());
                    //将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将 socketChannel 注册到selector 关注的事件为OP_READ 同时给socketChannel 关联一个buffer
                    socketChannel.register(selector,SelectionKey.OP_READ,ByteBuffer.allocate(1024));

                }
                if (key.isReadable()){ //发生 OP_READ 事件
                    //通过key反向获取 socketChannel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);

                    System.out.println("form client " + new String(buffer.array()));
                }
                //手动从集合中移除当前的selectionKey 防止重复操作
                keyIterator.remove();
            }
        }

    }
}
